import { Component } from '@angular/core';

import { Platform, Events, AlertController, App, List, ModalController, NavParams, NavController, LoadingController } from 'ionic-angular';

import { InfoDetailService } from './detail.service';

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

import { Config } from '../../../providers/config';

import { Common } from '../../../providers/common';

import { Storage } from '@ionic/storage';

// pdf容器
import { PdfViewerComponent } from 'ng2-pdf-viewer';

import _ from 'lodash';

@Component({
  selector: 'page-info-detail',
  templateUrl: './detail.html',
  providers: [InfoDetailService]
})
export class
  InfoDetailPage {
  moa_page_name: any = "page-info-detail";
  moa_page_explain: any = "信息中心详情";

  info: any = {};

  attachList = [];

  loading: any;

  pdfLink: SafeResourceUrl;

  zoom = 1;

  mfieldContent: any = "";

  pdfBase64: any;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public sanitizer: DomSanitizer,
    public platform: Platform,
    public storage: Storage,
    public navParams: NavParams,
    public loadingCtrl: LoadingController,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public common: Common,
    public events: Events,
    public infoDetailService: InfoDetailService,
    public config: Config
  ) {
    let that = this;
    this.info = this.navParams.data;
    console.log(this.info);
    if (this.info.isRemote === 'true') {
      this.info.isRemote = true;
    } else {
      this.info.isRemote = false;
    }

    switch (this.info.remark2) {
      case "Info5648":
        this.moa_page_explain = "正式发文 - 详情";
        break;
      case "Info2167":
        this.moa_page_explain = "通告公告 - 详情";
        break;
      case "Info8181":
        this.moa_page_explain = "温馨提示 - 详情";
        break;
    }

    //   /**
    //  * [function 解决pdf加载错误异常处理]
    //  */
    //   PdfViewerComponent.prototype["loadPDF"] = function() {
    //     var _this = this;
    //     if (!this.src) {
    //       return;
    //     }
    //     window['PDFJS'].getDocument(this.src).then(function(pdf) {
    //       _this._pdf = pdf;
    //       _this.afterLoadComplete.emit(pdf);
    //       _this.update();
    //     }).catch(function(err) {
    //       console.info('-----------------------------');
    //       console.info(err);
    //       that.pdfLoadCallBackFn(null);
    //       let alert = that.alertCtrl.create({
    //         title: '提示',
    //         subTitle: '正文加载失败,请稍候重试!',
    //         buttons: ['确认']
    //       });
    //       alert.present();
    //     });
    //   };

    this.initContent();
  }

  initContent() {
    let that = this;
    if (this.info.fbbosid) {
      this.infoDetailService.selectAllInfo(this.info.fbbosid).subscribe(data => {
        console.log("infoDetailService.selectAllInfo()", data);
        if (data) {
          if (data[0].NTKOCONT) {
            this.info.ntkoContent = data[0].NTKOCONT;
          } else if (data[0].ntkoContent) {
            this.info.ntkoContent = data[0].ntkoContent;
          }
          if (data[0].mfield) {
            this.info.mfield = data[0].mfield;
            this.formatMfield();
          }
          this.info.bostitle = data[0].bostitle;
          if (!this.info.isNotShowOrgnameAndBosdate) {
            this.info.bosdate = data[0].bosdate;
            this.info.orgname = data[0].orgname;
          }

          if (data[0].attachid) {
            this.info.InfoBwwf = data[0].attachid;
          } else if (data[0].InfoBwwf) {
            this.info.InfoBwwf = data[0].InfoBwwf;
          }
          if (data[0].qfrq) {
            this.info.qfrq = data[0].qfrq;
            this.info.oaType = "dispatch";
          }
          if (data[0].bomid) {
            this.info.bomid = data[0].bomid;
          }
          if (data[0].dirid) {
            this.info.dirid = data[0].dirid
          }
          console.log("this.info", this.info);
          this.getPdfContent();
        }
      });
    } else {
      this.getPdfContent();
    }
    if (this.info.mfield) {
      this.formatMfield();
    }
  }

  formatMfield() {
    let that = this;
    this.common.tranformImgLik(this.info.mfield, true).then(function (formatContent: any) {
      that.mfieldContent = that.sanitizer.bypassSecurityTrustHtml(formatContent);
      that.common.bindLinkersEvent("page-info-detail");
    });
  }

  getPdfContent() {
    let that = this;
    if (this.info.ntkoContent) {
      this.loading = this.loadingCtrl.create({
        content: '正在加载正文,请稍候...<br/>已完成：<span class="gfoa-load-pdf-percentage">0%</span>'
      });
      this.loading.present();
      console.info(that.info.ntkoContent);
      this.storage.get('id_token').then(token => {
        let from = this.navParams.get("from");
        if (this.info.bomid === "T_CM_CmAdFw" || this.info.dirid === "Info2167") {
          if (from && from === "flow") {
            that.pdfLink = that.config.server + "api/v1/common/attach/common/pdf/NO/true/" + that.info.isRemote + "/" + that.info.ntkoContent + ".pdf?access_token=" + token;
          } else {
            that.pdfLink = that.config.server + "api/v1/common/attach/common/pdf/NO/false/" + that.info.isRemote + "/" + that.info.ntkoContent + ".pdf?access_token=" + token;
          }
        } else {
          that.pdfLink = that.config.server + "api/v1/common/attach/common/pdf/" + that.info.isRemote + "/" + that.info.ntkoContent + ".pdf?access_token=" + token;
        }
      });
    }
  }

  /**
   * 加载文档完成回调
   * @param
   */
  pdfLoadCallBackFn($event) {
    this.loading.dismiss();
  }

  /**
   * 加载文档出错回调
   * @param
   */
  onPdfLoadError($event) {
    this.pdfLoadCallBackFn(null);
    let alert = this.alertCtrl.create({
      title: '提示',
      subTitle: '正文加载失败,请稍候重试!',
      buttons: ['确认']
    });
    alert.present();
  }

  /**
   * 加载文档进度
   * @param progressData
   */
  onLoadPdfProgress(progressData) {
    var p = ((progressData.loaded / progressData.total) * 100).toFixed(2) + "%";
    document.getElementsByClassName("gfoa-load-pdf-percentage")[0].innerHTML = p;
  }

  /**
   * pdf显示放大缩小
   * @param type
   */
  zoomPdf(type) {
    console.log(this.zoom);
    if (type == 'add') {
      if (this.zoom < 1.6) {
        this.zoom = this.zoom + 0.2;
      }
    } else {
      if (this.zoom > 0.6) {
        this.zoom = this.zoom - 0.2;
      }
    }
  }

  openFile(id, name) {
    this.common.openFile('common', 'normal', id, name, false);
  };

  ionViewDidLoad() {
    let that = this;
  }

}
